import { DefaultOptionType } from 'ant-design-vue/lib/vc-cascader';
import { findIndex } from 'lodash-es';
import { createSessionStorage } from '../cache';
/**
 * 获取本地api所有权限节点
 */
export function getNodes() {
  // 查找所有api列表下以 .class.ts 后缀的文件定义
  const apiFiles = import.meta.globEager('/src/api/**/*.class.ts');
  const result: any[] = [];
  Object.keys(apiFiles)
    .reverse()
    .forEach((item) => {
      const path: string = item.replace(/(^\/src\/api)|(.class.ts$)/g, () => '');
      const api = new apiFiles[item].default();
      if (api.nodes) {
        const nodes = api.nodes[path]
          ? { ...api.nodes.basic, ...api.nodes[path] }
          : { ...api.nodes.basic };
        result.push({ path: path.split('/').filter((item) => item), nodes });
      }
    });
  return result;
}

/**
 * API权限结点数据转为cascader选项数据
 * @param nodes
 * @returns
 */
export function nodesToCascader(nodes: any) {
  const options: DefaultOptionType[] = [];
  nodes.forEach((item: any) => {
    _nodesToCascader(item, options, 0);
  });
  return options;
}

function _nodesToCascader(pathArr: any[], options: DefaultOptionType[], index = 0) {
  const key = pathArr['path'][index];
  const _index = findIndex(options, (item) => item.label == key);
  if (_index >= 0) {
    _nodesToCascader(pathArr, <DefaultOptionType[]>options[_index].children, index + 1);
  } else {
    const isLast = pathArr['path'].length - 1 == index;
    const value: DefaultOptionType = {
      label: key,
      value: key,
    };
    if (isLast) {
      const _nodes: any[] = [];
      Object.keys(pathArr['nodes']).forEach((_key) => {
        _nodes.push({ label: _key, value: pathArr['nodes'][_key] });
      });
      value['children'] = _nodes;
    } else {
      value['children'] = [];
    }
    options.push(value);
    if (!isLast) {
      _nodesToCascader(
        pathArr,
        <DefaultOptionType[]>options[options.length - 1].children,
        index + 1,
      );
    }
  }
}

//验证节点是否显示
export function isNodeShow(router: string) {
  const nodes = createSessionStorage().get('auth_nodes');
  if (!nodes) return false;
  if (router.slice(0, 1) != '/') router = '/' + router;
  if (!nodes.includes(router)) return false;
  return true;
}
